package com.gregbugaj.nscaffold.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import com.gregbugaj.nscaffold.generator.artifact.Artifact;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * Utility class to help us work with templates
 * @author gbugaj
 *
 */
public class TemplateUtil {

	private static Configuration cfg; 

	static{
		// - Create a configuration instance
		cfg = new Configuration();
	}

	public  static String merge(String templatePath, Map<String, Object> model) {
		try {			
			// Get template object
			Template template = cfg.getTemplate(templatePath);
			ByteArrayOutputStream out=new ByteArrayOutputStream();
			PrintWriter writer=new PrintWriter(out);
			// Merge the data-model and the template
			template.process(model, writer);			
			return new String(out.toByteArray());
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void mergeToAsset(Artifact artifact,String templatePath, Map<String, Object> model) {
		try {
			// Get template object
			Template template = cfg.getTemplate(templatePath);
			ByteArrayOutputStream out=new ByteArrayOutputStream();
			PrintWriter writer=new PrintWriter(out);
			// Merge the data-model and the template
			template.process(model, writer);			
			artifact.setContent(new String(out.toByteArray()));
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
